import express from 'express';
import { checkSchema, validationResult } from 'express-validator'  
import util from 'utility'
import jwt from 'jsonwebtoken';  

const router = express.Router();

// 生成JWT令牌  
function generateToken(user) {  
    const secretKey = 'qfdixon'; // 替换为你的密钥  
    return jwt.sign( user , secretKey, { expiresIn: '48h' });  
}  


// 用户注册

router.post('/reg', checkSchema({
    name:{ notEmpty: true, errorMessage: '用户名不能为空' },
    pwd:{ notEmpty: true, errorMessage:'密码不能为空' }
}), async(req,res)=>{
    res.validator();  // 对于请求参数进行校验
    
    const { name,pwd} = req.body;
    await req.prisma.user.create({
        data:{
            name,
            pwd
        }
    })
    res.success('注册成功')

})


// 登录业务
router.post('/login', checkSchema({ 
    name:{ notEmpty: true, errorMessage: '用户名不能为空' },
    pwd:{ notEmpty: true, errorMessage:'密码不能为空' }
}) ,async (req,res)=>{
    
    const { name ,pwd} = req.body;
    const user = await req.prisma.user.findFirst({
        where:{
            name
        },
        include:{
            group: true
        }
    })

    if(user){
        const  token = generateToken(user);
        if(pwd === user.pwd) {
            res.success({ token, group: user.group })
        } else {
            res.fail('密码不正确')
        }
    }else {
        res.fail('用户不存在')
    }
})


router.post('/user/list', async (req,res)=>{
    const list = await req.prisma.user.findMany({
        where:{}
    })
    res.success(list)
})


router.post('/user/update', async (req,res)=>{
    const { uid, groupid } = req.body;
    const list = await req.prisma.user.update({
        where:{
            uid
        },
        data:{
            groupid
        }
    })
    res.success(list)
})







export default router;